package com.example.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.pojo.Dict;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Excel阅读器
 *
 * @author wsl
 */
public class EasyExcelGenerator {


    /**
     * 导出下载Excel文件
     * @param response 响应对象
     * @param fileName 生成的文件名称
     * @param head 数据模型
     * @param tableName 表格名称
     * @param list Excel表格数据集合 ofType要求用注解标明要打印的数据
     */
    public static void write(HttpServletResponse response,String fileName, Class head,String tableName,List list){
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), head).sheet(tableName).doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出Excel表格到指定文件中
     * @param filePath 导出数据的文件路径
     * @param head 数据模型
     * @param tableName 表格名称
     * @param list 数据集合
     */
    public static void write(String filePath, Class head, String tableName, List list){
        EasyExcel.write(filePath, head).sheet(tableName)
                .doWrite(list);
    }

    /**
     * 读取指定Excel文件中的数据
     * @param filePath 文件路径
     * @param head 数据模型
     * @param readListener 读取策略
     */
    public static void read(String filePath, Class head, ReadListener readListener){
        // 读取文件路径
        //调用方法实现读取操作
        EasyExcel.read(filePath, head ,readListener).sheet().doRead();
    }

    public static void main(String[] args) {
//        //设置excel文件路径和文件名称
        String filePath = "C:\\Users\\Administrator\\Desktop\\新建文件夹\\用户表.xlsx";
        Class head = Dict.class;
//        String tableName = "字典表";
//        List<Dict>  list  = new ArrayList<Dict>();
//        for (int i=0;i<10;i++) {
//            list.add(new Dict().setId(i).setName("ppat").setCode(i + "aaa"));
//        }
//        write(filePath,head,tableName,list);
        AnalysisEventListener<Dict> analysisEventListener = new AnalysisEventListener<Dict>() {
            @Override
            public void invoke(Dict dict, AnalysisContext analysisContext) {
                System.out.println(dict);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                System.out.println(headMap);
            }
        };

        read(filePath,head,analysisEventListener);
    }
}
